/**
 * 系统设置管理器 - 负责系统设置页面的交互功能
 * 包含用户管理、角色权限、系统配置、安全设置、日志管理等功能
 */
class SystemSettingsManager {
    constructor() {
        this.currentTab = 'users';
        this.users = [];
        this.roles = [];
        this.settings = {};
        this.logs = [];
        this.selectedUsers = new Set();
        this.selectedRoles = new Set();
        this.pagination = {
            page: 1,
            pageSize: 10,
            total: 0
        };
        
        this.init();
    }

    /**
     * 初始化系统设置管理器
     */
    init() {
        this.loadSettings();
        this.bindEvents();
        this.loadUsers();
        this.loadRoles();
        this.loadSystemInfo();
    }

    /**
     * 绑定事件处理
     */
    bindEvents() {
        // 标签切换
        document.querySelectorAll('.settings-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                this.switchTab(tab.dataset.tab);
            });
        });

        // 用户管理事件
        document.getElementById('addUserBtn')?.addEventListener('click', () => {
            this.showUserModal();
        });

        document.getElementById('refreshUsersBtn')?.addEventListener('click', () => {
            this.loadUsers();
            this.showNotification('用户列表已刷新', 'success');
        });

        document.getElementById('searchUsers')?.addEventListener('input', (e) => {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.searchUsers(e.target.value);
            }, 500);
        });

        // 角色管理事件
        document.getElementById('addRoleBtn')?.addEventListener('click', () => {
            this.showRoleModal();
        });

        document.getElementById('refreshRolesBtn')?.addEventListener('click', () => {
            this.loadRoles();
            this.showNotification('角色列表已刷新', 'success');
        });

        // 系统配置事件
        document.getElementById('saveSettingsBtn')?.addEventListener('click', () => {
            this.saveSettings();
        });

        document.getElementById('resetSettingsBtn')?.addEventListener('click', () => {
            this.resetSettings();
        });

        document.getElementById('testConnectionBtn')?.addEventListener('click', () => {
            this.testConnection();
        });

        // 安全设置事件
        document.getElementById('changePasswordBtn')?.addEventListener('click', () => {
            this.showChangePasswordModal();
        });

        document.getElementById('generateApiKeyBtn')?.addEventListener('click', () => {
            this.generateApiKey();
        });

        document.getElementById('refreshApiKeyBtn')?.addEventListener('click', () => {
            this.refreshApiKey();
        });

        // 日志管理事件
        document.getElementById('refreshLogsBtn')?.addEventListener('click', () => {
            this.loadLogs();
            this.showNotification('日志已刷新', 'success');
        });

        document.getElementById('exportLogsBtn')?.addEventListener('click', () => {
            this.exportLogs();
        });

        document.getElementById('clearLogsBtn')?.addEventListener('click', () => {
            this.clearLogs();
        });

        // 数据备份事件
        document.getElementById('backupNowBtn')?.addEventListener('click', () => {
            this.createBackup();
        });

        document.getElementById('restoreBtn')?.addEventListener('click', () => {
            this.showRestoreModal();
        });

        // 列表事件（事件委托）
        document.getElementById('usersList')?.addEventListener('click', (e) => {
            const userRow = e.target.closest('.user-row');
            if (!userRow) return;

            const userId = userRow.dataset.userId;

            // 编辑用户
            if (e.target.closest('.edit-user-btn')) {
                e.preventDefault();
                this.editUser(userId);
            }

            // 删除用户
            if (e.target.closest('.delete-user-btn')) {
                e.preventDefault();
                this.deleteUser(userId);
            }

            // 重置密码
            if (e.target.closest('.reset-password-btn')) {
                e.preventDefault();
                this.resetUserPassword(userId);
            }

            // 切换状态
            if (e.target.closest('.toggle-status-btn')) {
                e.preventDefault();
                this.toggleUserStatus(userId);
            }

            // 选择用户
            if (e.target.closest('.user-checkbox')) {
                this.toggleUserSelection(userId, e.target.checked);
            }
        });

        document.getElementById('rolesList')?.addEventListener('click', (e) => {
            const roleRow = e.target.closest('.role-row');
            if (!roleRow) return;

            const roleId = roleRow.dataset.roleId;

            // 编辑角色
            if (e.target.closest('.edit-role-btn')) {
                e.preventDefault();
                this.editRole(roleId);
            }

            // 删除角色
            if (e.target.closest('.delete-role-btn')) {
                e.preventDefault();
                this.deleteRole(roleId);
            }

            // 权限设置
            if (e.target.closest('.permissions-btn')) {
                e.preventDefault();
                this.showPermissionsModal(roleId);
            }
        });

        // 批量操作
        document.getElementById('selectAllUsers')?.addEventListener('change', (e) => {
            this.toggleSelectAllUsers(e.target.checked);
        });

        document.getElementById('batchDeleteUsers')?.addEventListener('click', () => {
            this.batchDeleteUsers();
        });

        document.getElementById('batchActivateUsers')?.addEventListener('click', () => {
            this.batchActivateUsers(true);
        });

        document.getElementById('batchDeactivateUsers')?.addEventListener('click', () => {
            this.batchActivateUsers(false);
        });

        // 分页事件
        document.getElementById('prevPage')?.addEventListener('click', () => {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadCurrentData();
            }
        });

        document.getElementById('nextPage')?.addEventListener('click', () => {
            if (this.pagination.page < this.getTotalPages()) {
                this.pagination.page++;
                this.loadCurrentData();
            }
        });

        // 文件上传事件
        document.getElementById('logoUpload')?.addEventListener('change', (e) => {
            this.uploadLogo(e.target.files[0]);
        });

        document.getElementById('faviconUpload')?.addEventListener('change', (e) => {
            this.uploadFavicon(e.target.files[0]);
        });
    }

    /**
     * 切换标签页
     */
    switchTab(tabName) {
        this.currentTab = tabName;

        // 更新标签样式
        document.querySelectorAll('.settings-tab').forEach(tab => {
            tab.classList.remove('bg-blue-600', 'text-white');
            tab.classList.add('text-gray-600', 'hover:text-gray-800');
        });

        const activeTab = document.querySelector(`[data-tab="${tabName}"]`);
        if (activeTab) {
            activeTab.classList.remove('text-gray-600', 'hover:text-gray-800');
            activeTab.classList.add('bg-blue-600', 'text-white');
        }

        // 显示对应内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });

        const targetContent = document.getElementById(`${tabName}Tab`);
        if (targetContent) {
            targetContent.classList.remove('hidden');
        }

        // 加载对应数据
        this.loadCurrentData();
    }

    /**
     * 加载当前标签页数据
     */
    loadCurrentData() {
        switch (this.currentTab) {
            case 'users':
                this.loadUsers();
                break;
            case 'roles':
                this.loadRoles();
                break;
            case 'settings':
                this.loadSettings();
                break;
            case 'security':
                this.loadSecuritySettings();
                break;
            case 'logs':
                this.loadLogs();
                break;
        }
    }

    /**
     * 加载系统设置
     */
    async loadSettings() {
        try {
            const response = await fetch('/api/system/settings');
            const result = await response.json();

            if (result.code === 200) {
                this.settings = result.data;
                this.updateSettingsDisplay();
            } else {
                this.showNotification('加载设置失败', 'error');
            }
        } catch (error) {
            console.error('加载设置出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 更新设置显示
     */
    updateSettingsDisplay() {
        // 基础设置
        document.getElementById('systemName')?.replaceWith(
            `<input type="text" id="systemName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.system_name || ''}">`
        );

        document.getElementById('systemDescription')?.replaceWith(
            `<textarea id="systemDescription" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">${this.settings.system_description || ''}</textarea>`
        );

        document.getElementById('adminEmail')?.replaceWith(
            `<input type="email" id="adminEmail" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.admin_email || ''}">`
        );

        // 数据库设置
        document.getElementById('dbHost')?.replaceWith(
            `<input type="text" id="dbHost" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.db_host || ''}">`
        );

        document.getElementById('dbPort')?.replaceWith(
            `<input type="number" id="dbPort" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.db_port || ''}">`
        );

        document.getElementById('dbName')?.replaceWith(
            `<input type="text" id="dbName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.db_name || ''}">`
        );

        // 文件存储设置
        document.getElementById('uploadPath')?.replaceWith(
            `<input type="text" id="uploadPath" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.upload_path || ''}">`
        );

        document.getElementById('maxFileSize')?.replaceWith(
            `<input type="number" id="maxFileSize" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.max_file_size || ''}">`
        );

        // 邮件设置
        document.getElementById('smtpServer')?.replaceWith(
            `<input type="text" id="smtpServer" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.smtp_server || ''}">`
        );

        document.getElementById('smtpPort')?.replaceWith(
            `<input type="number" id="smtpPort" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.smtp_port || ''}">`
        );

        document.getElementById('smtpUsername')?.replaceWith(
            `<input type="text" id="smtpUsername" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.smtp_username || ''}">`
        );

        document.getElementById('smtpPassword')?.replaceWith(
            `<input type="password" id="smtpPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${this.settings.smtp_password || ''}">`
        );
    }

    /**
     * 保存设置
     */
    async saveSettings() {
        const settingsData = {
            system_name: document.getElementById('systemName')?.value,
            system_description: document.getElementById('systemDescription')?.value,
            admin_email: document.getElementById('adminEmail')?.value,
            db_host: document.getElementById('dbHost')?.value,
            db_port: parseInt(document.getElementById('dbPort')?.value),
            db_name: document.getElementById('dbName')?.value,
            upload_path: document.getElementById('uploadPath')?.value,
            max_file_size: parseInt(document.getElementById('maxFileSize')?.value),
            smtp_server: document.getElementById('smtpServer')?.value,
            smtp_port: parseInt(document.getElementById('smtpPort')?.value),
            smtp_username: document.getElementById('smtpUsername')?.value,
            smtp_password: document.getElementById('smtpPassword')?.value
        };

        try {
            const response = await fetch('/api/system/settings', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(settingsData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('设置保存成功', 'success');
                this.settings = { ...this.settings, ...settingsData };
            } else {
                this.showNotification(result.message || '设置保存失败', 'error');
            }
        } catch (error) {
            console.error('保存设置出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 重置设置
     */
    resetSettings() {
        if (!confirm('确定要重置所有设置为默认值吗？此操作不可恢复。')) return;

        try {
            const response = await fetch('/api/system/settings/reset', {
                method: 'POST'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('设置已重置为默认值', 'success');
                this.loadSettings();
            } else {
                this.showNotification(result.message || '重置设置失败', 'error');
            }
        } catch (error) {
            console.error('重置设置出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 测试连接
     */
    async testConnection() {
        const button = document.getElementById('testConnectionBtn');
        const originalText = button.textContent;
        
        button.disabled = true;
        button.textContent = '测试中...';

        try {
            const response = await fetch('/api/system/test-connection');
            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('连接测试成功', 'success');
            } else {
                this.showNotification(result.message || '连接测试失败', 'error');
            }
        } catch (error) {
            console.error('测试连接出错:', error);
            this.showNotification('网络连接异常', 'error');
        } finally {
            button.disabled = false;
            button.textContent = originalText;
        }
    }

    /**
     * 加载用户列表
     */
    async loadUsers() {
        try {
            const params = new URLSearchParams({
                page: this.pagination.page,
                page_size: this.pagination.pageSize
            });

            const response = await fetch(`/api/system/users?${params}`);
            const result = await response.json();

            if (result.code === 200) {
                this.users = result.data.users;
                this.pagination.total = result.data.total;
                this.renderUsers();
                this.updatePagination();
            } else {
                this.showNotification('加载用户列表失败', 'error');
            }
        } catch (error) {
            console.error('加载用户列表出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 渲染用户列表
     */
    renderUsers() {
        const container = document.getElementById('usersList');
        if (!container) return;

        if (this.users.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 text-slate-500">
                    <i class="fas fa-users text-4xl mb-4"></i>
                    <p>暂无用户数据</p>
                    <button class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="systemSettingsManager.showUserModal()">
                        添加用户
                    </button>
                </div>
            `;
            return;
        }

        const html = this.users.map(user => `
            <tr class="user-row hover:bg-slate-50" data-user-id="${user.id}">
                <td class="p-4">
                    <input type="checkbox" class="user-checkbox rounded" 
                           ${this.selectedUsers.has(user.id) ? 'checked' : ''}>
                </td>
                <td class="p-4">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-user text-blue-600"></i>
                        </div>
                        <div>
                            <p class="font-medium text-slate-800">${user.username}</p>
                            <p class="text-sm text-slate-500">${user.email}</p>
                        </div>
                    </div>
                </td>
                <td class="p-4">
                    ${this.getRoleBadges(user.roles)}
                </td>
                <td class="p-4">
                    ${user.last_login ? new Date(user.last_login).toLocaleDateString('zh-CN') : '从未登录'}
                </td>
                <td class="p-4">
                    ${this.getUserStatusBadge(user.is_active)}
                </td>
                <td class="p-4">
                    <div class="flex space-x-2">
                        <button class="edit-user-btn text-blue-600 hover:text-blue-800 text-sm">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="reset-password-btn text-yellow-600 hover:text-yellow-800 text-sm">
                            <i class="fas fa-key"></i>
                        </button>
                        <button class="toggle-status-btn text-${user.is_active ? 'orange' : 'green'}-600 hover:text-${user.is_active ? 'orange' : 'green'}-800 text-sm">
                            <i class="fas fa-${user.is_active ? 'pause' : 'play'}"></i>
                        </button>
                        <button class="delete-user-btn text-red-600 hover:text-red-800 text-sm">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');

        container.innerHTML = html;
    }

    /**
     * 获取角色标签
     */
    getRoleBadges(roles) {
        if (!roles || roles.length === 0) {
            return '<span class="text-sm text-slate-500">无角色</span>';
        }

        return roles.map(role => 
            `<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">${role.name}</span>`
        ).join(' ');
    }

    /**
     * 获取用户状态标签
     */
    getUserStatusBadge(isActive) {
        return isActive ? 
            '<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">活跃</span>' :
            '<span class="px-2 py-1 bg-red-100 text-red-700 text-xs rounded-full">禁用</span>';
    }

    /**
     * 显示用户模态框
     */
    showUserModal(user = null) {
        const isEdit = !!user;
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="userModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-md">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">${isEdit ? '编辑用户' : '添加用户'}</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="systemSettingsManager.closeModal('userModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <form id="userForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                            <input type="text" id="username" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${user?.username || ''}" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                            <input type="email" id="email" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${user?.email || ''}" required>
                        </div>
                        
                        ${!isEdit ? `
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
                            <input type="password" id="password" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">确认密码</label>
                            <input type="password" id="confirmPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        ` : ''}
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">角色</label>
                            <div class="space-y-2">
                                ${this.roles.map(role => `
                                    <label class="flex items-center">
                                        <input type="checkbox" name="roles" value="${role.id}" class="mr-2" ${user?.roles?.some(r => r.id === role.id) ? 'checked' : ''}>
                                        <span class="text-sm">${role.name}</span>
                                    </label>
                                `).join('')}
                            </div>
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="isActive" class="mr-2" ${user?.is_active ? 'checked' : ''}>
                                <span class="text-sm">启用用户</span>
                            </label>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="systemSettingsManager.closeModal('userModal')">取消</button>
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">${isEdit ? '更新' : '创建'}</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 绑定表单提交事件
        const form = document.getElementById('userForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveUser(form, user?.id);
        });
    }

    /**
     * 保存用户
     */
    async saveUser(form, userId = null) {
        const formData = new FormData(form);
        const selectedRoles = Array.from(document.querySelectorAll('input[name="roles"]:checked')).map(cb => cb.value);
        
        const userData = {
            username: document.getElementById('username').value,
            email: document.getElementById('email').value,
            is_active: document.getElementById('isActive').checked,
            roles: selectedRoles
        };

        if (!userId) {
            userData.password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (userData.password !== confirmPassword) {
                this.showNotification('两次输入的密码不一致', 'error');
                return;
            }
        }

        try {
            const url = userId ? `/api/system/users/${userId}` : '/api/system/users';
            const method = userId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification(userId ? '用户更新成功' : '用户创建成功', 'success');
                this.closeModal('userModal');
                this.loadUsers();
            } else {
                this.showNotification(result.message || '用户保存失败', 'error');
            }
        } catch (error) {
            console.error('保存用户出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 编辑用户
     */
    editUser(userId) {
        const user = this.users.find(u => u.id === userId);
        if (user) {
            this.showUserModal(user);
        }
    }

    /**
     * 删除用户
     */
    async deleteUser(userId) {
        if (!confirm('确定要删除这个用户吗？')) return;

        try {
            const response = await fetch(`/api/system/users/${userId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('用户删除成功', 'success');
                this.loadUsers();
            } else {
                this.showNotification(result.message || '用户删除失败', 'error');
            }
        } catch (error) {
            console.error('删除用户出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 重置用户密码
     */
    async resetUserPassword(userId) {
        const user = this.users.find(u => u.id === userId);
        if (!user) return;

        const newPassword = prompt(`请输入 ${user.username} 的新密码:`);
        if (!newPassword) return;

        try {
            const response = await fetch(`/api/system/users/${userId}/reset-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ password: newPassword })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('密码重置成功', 'success');
            } else {
                this.showNotification(result.message || '密码重置失败', 'error');
            }
        } catch (error) {
            console.error('重置密码出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 切换用户状态
     */
    async toggleUserStatus(userId) {
        const user = this.users.find(u => u.id === userId);
        if (!user) return;

        try {
            const response = await fetch(`/api/system/users/${userId}/toggle-status`, {
                method: 'POST'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification(`用户已${user.is_active ? '禁用' : '启用'}`, 'success');
                this.loadUsers();
            } else {
                this.showNotification(result.message || '状态切换失败', 'error');
            }
        } catch (error) {
            console.error('切换用户状态出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 加载角色列表
     */
    async loadRoles() {
        try {
            const response = await fetch('/api/system/roles');
            const result = await response.json();

            if (result.code === 200) {
                this.roles = result.data;
                this.renderRoles();
            } else {
                this.showNotification('加载角色列表失败', 'error');
            }
        } catch (error) {
            console.error('加载角色列表出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 渲染角色列表
     */
    renderRoles() {
        const container = document.getElementById('rolesList');
        if (!container) return;

        if (this.roles.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 text-slate-500">
                    <i class="fas fa-user-tag text-4xl mb-4"></i>
                    <p>暂无角色数据</p>
                    <button class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="systemSettingsManager.showRoleModal()">
                        添加角色
                    </button>
                </div>
            `;
            return;
        }

        const html = this.roles.map(role => `
            <tr class="role-row hover:bg-slate-50" data-role-id="${role.id}">
                <td class="p-4">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-user-tag text-purple-600"></i>
                        </div>
                        <div>
                            <p class="font-medium text-slate-800">${role.name}</p>
                            <p class="text-sm text-slate-500">${role.description}</p>
                        </div>
                    </div>
                </td>
                <td class="p-4">
                    <span class="text-sm text-slate-600">${role.user_count || 0} 个用户</span>
                </td>
                <td class="p-4">
                    ${role.is_system ? 
                        '<span class="px-2 py-1 bg-orange-100 text-orange-700 text-xs rounded-full">系统角色</span>' :
                        '<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">自定义角色</span>'
                    }
                </td>
                <td class="p-4">
                    <div class="flex space-x-2">
                        <button class="edit-role-btn text-blue-600 hover:text-blue-800 text-sm" ${role.is_system ? 'disabled' : ''}>
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="permissions-btn text-green-600 hover:text-green-800 text-sm">
                            <i class="fas fa-shield-alt"></i>
                        </button>
                        <button class="delete-role-btn text-red-600 hover:text-red-800 text-sm" ${role.is_system ? 'disabled' : ''}>
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');

        container.innerHTML = html;
    }

    /**
     * 显示角色模态框
     */
    showRoleModal(role = null) {
        const isEdit = !!role;
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="roleModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-md">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">${isEdit ? '编辑角色' : '添加角色'}</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="systemSettingsManager.closeModal('roleModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <form id="roleForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">角色名称</label>
                            <input type="text" id="roleName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${role?.name || ''}" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">角色描述</label>
                            <textarea id="roleDescription" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">${role?.description || ''}</textarea>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="systemSettingsManager.closeModal('roleModal')">取消</button>
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">${isEdit ? '更新' : '创建'}</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 绑定表单提交事件
        const form = document.getElementById('roleForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveRole(form, role?.id);
        });
    }

    /**
     * 保存角色
     */
    async saveRole(form, roleId = null) {
        const roleData = {
            name: document.getElementById('roleName').value,
            description: document.getElementById('roleDescription').value
        };

        try {
            const url = roleId ? `/api/system/roles/${roleId}` : '/api/system/roles';
            const method = roleId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(roleData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification(roleId ? '角色更新成功' : '角色创建成功', 'success');
                this.closeModal('roleModal');
                this.loadRoles();
            } else {
                this.showNotification(result.message || '角色保存失败', 'error');
            }
        } catch (error) {
            console.error('保存角色出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 编辑角色
     */
    editRole(roleId) {
        const role = this.roles.find(r => r.id === roleId);
        if (role) {
            this.showRoleModal(role);
        }
    }

    /**
     * 删除角色
     */
    async deleteRole(roleId) {
        const role = this.roles.find(r => r.id === roleId);
        if (!role || role.is_system) {
            this.showNotification('系统角色不能删除', 'warning');
            return;
        }

        if (!confirm('确定要删除这个角色吗？')) return;

        try {
            const response = await fetch(`/api/system/roles/${roleId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('角色删除成功', 'success');
                this.loadRoles();
            } else {
                this.showNotification(result.message || '角色删除失败', 'error');
            }
        } catch (error) {
            console.error('删除角色出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 显示权限设置模态框
     */
    showPermissionsModal(roleId) {
        const role = this.roles.find(r => r.id === roleId);
        if (!role) return;

        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="permissionsModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">权限设置 - ${role.name}</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="systemSettingsManager.closeModal('permissionsModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <h4 class="font-medium text-gray-700 mb-2">用户管理</h4>
                                <div class="space-y-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="user_view">
                                        <span class="text-sm">查看用户</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="user_create">
                                        <span class="text-sm">创建用户</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="user_edit">
                                        <span class="text-sm">编辑用户</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="user_delete">
                                        <span class="text-sm">删除用户</span>
                                    </label>
                                </div>
                            </div>
                            
                            <div>
                                <h4 class="font-medium text-gray-700 mb-2">角色管理</h4>
                                <div class="space-y-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="role_view">
                                        <span class="text-sm">查看角色</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="role_create">
                                        <span class="text-sm">创建角色</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="role_edit">
                                        <span class="text-sm">编辑角色</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="role_delete">
                                        <span class="text-sm">删除角色</span>
                                    </label>
                                </div>
                            </div>
                            
                            <div>
                                <h4 class="font-medium text-gray-700 mb-2">系统管理</h4>
                                <div class="space-y-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="system_view">
                                        <span class="text-sm">查看设置</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="system_edit">
                                        <span class="text-sm">编辑设置</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="system_backup">
                                        <span class="text-sm">数据备份</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="system_restore">
                                        <span class="text-sm">数据恢复</span>
                                    </label>
                                </div>
                            </div>
                            
                            <div>
                                <h4 class="font-medium text-gray-700 mb-2">业务功能</h4>
                                <div class="space-y-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="analysis_view">
                                        <span class="text-sm">查看分析</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="analysis_execute">
                                        <span class="text-sm">执行分析</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="report_view">
                                        <span class="text-sm">查看报告</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="permission-checkbox mr-2" data-permission="report_generate">
                                        <span class="text-sm">生成报告</span>
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="systemSettingsManager.closeModal('permissionsModal')">取消</button>
                            <button type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="systemSettingsManager.savePermissions(${roleId})">保存权限</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 加载当前权限
        this.loadRolePermissions(roleId);
    }

    /**
     * 加载角色权限
     */
    async loadRolePermissions(roleId) {
        try {
            const response = await fetch(`/api/system/roles/${roleId}/permissions`);
            const result = await response.json();

            if (result.code === 200) {
                const permissions = result.data;
                permissions.forEach(permission => {
                    const checkbox = document.querySelector(`input[data-permission="${permission}"]`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
            }
        } catch (error) {
            console.error('加载权限出错:', error);
        }
    }

    /**
     * 保存权限
     */
    async savePermissions(roleId) {
        const permissions = Array.from(document.querySelectorAll('.permission-checkbox:checked'))
            .map(cb => cb.dataset.permission);

        try {
            const response = await fetch(`/api/system/roles/${roleId}/permissions`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ permissions })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('权限保存成功', 'success');
                this.closeModal('permissionsModal');
            } else {
                this.showNotification(result.message || '权限保存失败', 'error');
            }
        } catch (error) {
            console.error('保存权限出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 加载安全设置
     */
    async loadSecuritySettings() {
        try {
            const response = await fetch('/api/system/security-settings');
            const result = await response.json();

            if (result.code === 200) {
                this.updateSecuritySettings(result.data);
            }
        } catch (error) {
            console.error('加载安全设置出错:', error);
        }
    }

    /**
     * 更新安全设置显示
     */
    updateSecuritySettings(settings) {
        document.getElementById('sessionTimeout')?.replaceWith(
            `<input type="number" id="sessionTimeout" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${settings.session_timeout || 30}" min="5" max="480">`
        );

        document.getElementById('maxLoginAttempts')?.replaceWith(
            `<input type="number" id="maxLoginAttempts" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${settings.max_login_attempts || 5}" min="1" max="10">`
        );

        document.getElementById('passwordExpiry')?.replaceWith(
            `<input type="number" id="passwordExpiry" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${settings.password_expiry || 90}" min="0" max="365">`
        );

        document.getElementById('apiKey')?.replaceWith(
            `<input type="text" id="apiKey" class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50" value="${settings.api_key || ''}" readonly>`
        );
    }

    /**
     * 显示修改密码模态框
     */
    showChangePasswordModal() {
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="changePasswordModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-md">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">修改密码</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="systemSettingsManager.closeModal('changePasswordModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <form id="changePasswordForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">当前密码</label>
                            <input type="password" id="currentPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">新密码</label>
                            <input type="password" id="newPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">确认新密码</label>
                            <input type="password" id="confirmNewPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="systemSettingsManager.closeModal('changePasswordModal')">取消</button>
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">修改密码</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 绑定表单提交事件
        const form = document.getElementById('changePasswordForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.changePassword(form);
        });
    }

    /**
     * 修改密码
     */
    async changePassword(form) {
        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmNewPassword = document.getElementById('confirmNewPassword').value;

        if (newPassword !== confirmNewPassword) {
            this.showNotification('两次输入的新密码不一致', 'error');
            return;
        }

        try {
            const response = await fetch('/api/system/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    current_password: currentPassword,
                    new_password: newPassword
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('密码修改成功', 'success');
                this.closeModal('changePasswordModal');
            } else {
                this.showNotification(result.message || '密码修改失败', 'error');
            }
        } catch (error) {
            console.error('修改密码出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 生成API密钥
     */
    async generateApiKey() {
        try {
            const response = await fetch('/api/system/generate-api-key', {
                method: 'POST'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                document.getElementById('apiKey').value = result.data.api_key;
                this.showNotification('API密钥生成成功', 'success');
            } else {
                this.showNotification(result.message || 'API密钥生成失败', 'error');
            }
        } catch (error) {
            console.error('生成API密钥出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 刷新API密钥
     */
    async refreshApiKey() {
        if (!confirm('确定要刷新API密钥吗？这将使现有的密钥失效。')) return;

        await this.generateApiKey();
    }

    /**
     * 加载系统信息
     */
    async loadSystemInfo() {
        try {
            const response = await fetch('/api/system/info');
            const result = await response.json();

            if (result.code === 200) {
                this.updateSystemInfo(result.data);
            }
        } catch (error) {
            console.error('加载系统信息出错:', error);
        }
    }

    /**
     * 更新系统信息显示
     */
    updateSystemInfo(info) {
        const systemInfoContainer = document.getElementById('systemInfo');
        if (!systemInfoContainer) return;

        const html = `
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">系统版本</label>
                    <p class="text-sm text-gray-900">${info.version || '未知'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">运行时间</label>
                    <p class="text-sm text-gray-900">${this.formatUptime(info.uptime)}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Python版本</label>
                    <p class="text-sm text-gray-900">${info.python_version || '未知'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">数据库版本</label>
                    <p class="text-sm text-gray-900">${info.database_version || '未知'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">系统架构</label>
                    <p class="text-sm text-gray-900">${info.architecture || '未知'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">操作系统</label>
                    <p class="text-sm text-gray-900">${info.os || '未知'}</p>
                </div>
            </div>
        `;

        systemInfoContainer.innerHTML = html;
    }

    /**
     * 格式化运行时间
     */
    formatUptime(seconds) {
        if (!seconds) return '未知';
        
        const days = Math.floor(seconds / 86400);
        const hours = Math.floor((seconds % 86400) / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        
        return `${days}天 ${hours}小时 ${minutes}分钟`;
    }

    /**
     * 搜索用户
     */
    async searchUsers(keyword) {
        try {
            const response = await fetch(`/api/system/users/search?keyword=${encodeURIComponent(keyword)}`);
            const result = await response.json();

            if (result.code === 200) {
                this.users = result.data;
                this.renderUsers();
            }
        } catch (error) {
            console.error('搜索用户出错:', error);
        }
    }

    /**
     * 切换全选用户
     */
    toggleSelectAllUsers(checked) {
        this.users.forEach(user => {
            if (checked) {
                this.selectedUsers.add(user.id);
            } else {
                this.selectedUsers.delete(user.id);
            }
        });
        this.renderUsers();
    }

    /**
     * 切换用户选择
     */
    toggleUserSelection(userId, checked) {
        if (checked) {
            this.selectedUsers.add(userId);
        } else {
            this.selectedUsers.delete(userId);
        }
    }

    /**
     * 批量删除用户
     */
    async batchDeleteUsers() {
        if (this.selectedUsers.size === 0) {
            this.showNotification('请选择要删除的用户', 'warning');
            return;
        }

        if (!confirm(`确定要删除选中的 ${this.selectedUsers.size} 个用户吗？`)) return;

        try {
            const response = await fetch('/api/system/users/batch-delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_ids: Array.from(this.selectedUsers)
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('批量删除成功', 'success');
                this.selectedUsers.clear();
                this.loadUsers();
            } else {
                this.showNotification(result.message || '批量删除失败', 'error');
            }
        } catch (error) {
            console.error('批量删除出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 批量激活/停用用户
     */
    async batchActivateUsers(activate) {
        if (this.selectedUsers.size === 0) {
            this.showNotification('请选择要操作的用户', 'warning');
            return;
        }

        try {
            const response = await fetch('/api/system/users/batch-activate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_ids: Array.from(this.selectedUsers),
                    activate: activate
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification(`批量${activate ? '激活' : '停用'}成功`, 'success');
                this.selectedUsers.clear();
                this.loadUsers();
            } else {
                this.showNotification(result.message || '批量操作失败', 'error');
            }
        } catch (error) {
            console.error('批量操作出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 更新分页显示
     */
    updatePagination() {
        const totalPages = this.getTotalPages();
        
        // 更新页码显示
        document.getElementById('currentPage')?.replaceWith(
            `<span id="currentPage">${this.pagination.page}</span>`
        );
        
        document.getElementById('totalPages')?.replaceWith(
            `<span id="totalPages">${totalPages}</span>`
        );

        // 更新按钮状态
        const prevBtn = document.getElementById('prevPage');
        const nextBtn = document.getElementById('nextPage');
        
        if (prevBtn) {
            prevBtn.disabled = this.pagination.page <= 1;
            prevBtn.classList.toggle('opacity-50', this.pagination.page <= 1);
        }
        
        if (nextBtn) {
            nextBtn.disabled = this.pagination.page >= totalPages;
            nextBtn.classList.toggle('opacity-50', this.pagination.page >= totalPages);
        }
    }

    /**
     * 获取总页数
     */
    getTotalPages() {
        return Math.ceil(this.pagination.total / this.pagination.pageSize);
    }

    /**
     * 关闭模态框
     */
    closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.remove();
        }
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        const colors = {
            success: 'bg-green-500',
            error: 'bg-red-500',
            warning: 'bg-yellow-500',
            info: 'bg-blue-500'
        };

        notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full`;
        notification.textContent = message;

        document.body.appendChild(notification);

        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 100);

        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }

    /**
     * 销毁实例
     */
    destroy() {
        // 清理定时器
        if (this.searchTimeout) {
            clearTimeout(this.searchTimeout);
        }
    }
}

// 页面加载完成后初始化系统设置管理器
document.addEventListener('DOMContentLoaded', function() {
    window.systemSettingsManager = new SystemSettingsManager();
});

// 监听页面卸载事件
window.addEventListener('beforeunload', function() {
    if (window.systemSettingsManager) {
        window.systemSettingsManager.destroy();
    }
});